﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.Entity;
using Utilities;
using Home.Domain.Entities;
using Home.WebUI.Areas.Admin.Models.QuoteViewModel;
using System.Transactions;
using Home.WebUI.Models;

namespace Home.WebUI.Areas.Admin.Controllers
{
    public class QuoteController : Controller
    {
        private EFDbContext db = new EFDbContext();
        //
        // GET: /Admin/Quote/

        public ActionResult Index(IndexViewModel model, int page = 1)
        {
            //页面项数
            int pageSize = 10;
            var companys = db.Quotes.Include(q => q.CategoryEntitis).Include(q => q.BrandEntitis).OrderByDescending(c => c.CreateDate).Skip((page - 1) * pageSize).Take(pageSize);
            model.Quotes = companys;
            model.PagingInfo = new PagingInfo { CurrentPage = page, ItemsPerPage = pageSize, TotalItems = db.Companys.Count() };
            return View(model);
        }
        public ActionResult Details(int id)
        {
            IEnumerable<QuoteProduct> model = db.QuoteProducts.Where(q => q.QuoteId == id);
            return View(model);
        }
        [HttpPost]
        //提交报价
        public ActionResult QuoteSubmit(FormCollection from)
        {
            int QuoteId =Convert.ToInt32(from["QuoteId"]);//报价id
            using (TransactionScope transaction = new TransactionScope())
            {
                //已经有的产品，只修改价格
                foreach (var item in db.QuoteProducts.Where(q=>db.Products.Select(p=>p.Name).Contains(q.ProductName)).Where(q => q.QuoteId == QuoteId).ToList())
                {

                    #region 修改产品价格
                    Product model = db.Products.First(p => p.Name == item.ProductName);
                    model.Price = item.Price; 
                    #endregion

                    #region 添加价格列表
                    ProductPrice productPrice = new ProductPrice();
                    productPrice.CreateDate = DateTime.Now;
                    productPrice.Price = item.Price;
                    productPrice.ProductId = model.Id;
                    db.ProductPrices.Add(productPrice); 
                    #endregion
                }
                foreach (var item in db.QuoteProducts.Include(q => q.QuoteEntitis).AsNoTracking().Where(q => !db.Products.Select(p => p.Name).Contains(q.ProductName)).Where(q => q.QuoteId == QuoteId).ToList())
                {
                    #region 添加产品
                    Product model = new Product();
                    model.BrandId = item.QuoteEntitis.BrandId;
                    model.CategoryId = item.QuoteEntitis.CategoryId;
                    model.CreateDate = DateTime.Now;
                    model.Description = item.Description;
                    model.Name = item.ProductName;
                    model.Price = item.Price;
                    db.Products.Add(model); 
                    #endregion
                    db.SaveChanges();//保存，为了生成Id
                    #region 添加价格列表
                    ProductPrice productPrice = new ProductPrice();
                    productPrice.CreateDate = DateTime.Now;
                    productPrice.Price = item.Price;
                    productPrice.ProductId = model.Id;
                    db.ProductPrices.Add(productPrice);
                    #endregion
                }
                #region 更新报价表状态为已发布
                Quote quteModel = new Quote();
                quteModel.Id = QuoteId;
                db.Quotes.Attach(quteModel);
                quteModel.State = 1;
                quteModel.SubmitDate = DateTime.Now;
                #endregion

                db.SaveChanges();
                transaction.Complete();
            }
            return View();
        }

        public ActionResult Create()
        {
            ProductCreateDropDownList();
            return View();
        }
        [HttpPost]
        public ActionResult Create(CreateViewModel model)
        {
            int quoteid;
            using (TransactionScope transaction = new TransactionScope())
            {
                #region 添加报价
                Quote quoteModel = new Quote();
                quoteModel.BrandId = model.BrandId;
                quoteModel.CategoryId = model.ChildId == null ? model.ParentId : model.ChildId;
                quoteModel.CreateDate = DateTime.Now;
                quoteModel.State = 0;
                db.Quotes.Add(quoteModel);
                db.SaveChanges();
                quoteid =Convert.ToInt32(quoteModel.Id);
                #endregion

                #region 报价详细
                int rownumber = 0;//开始行
                HttpPostedFileBase fileasve = Request.Files["QuoteDetails"];
                DataTable dt = ExclHelper.ImportDataTableFromExcel(fileasve.InputStream, rownumber);
                foreach (DataRow item in dt.Rows)
                {
                    QuoteProduct content = new QuoteProduct();
                    content.QuoteId = quoteModel.Id;
                    content.Description = item["描述"].ToString();
                    content.Price = Convert.ToDecimal(item["价格"]);
                    content.ProductName = item["名称"].ToString();
                    db.QuoteProducts.Add(content);
                }
                db.SaveChanges();
                #endregion

                transaction.Complete();
            }
            return RedirectToAction("Details", new { id = quoteid });
        }
        #region 上传报价Ajax下拉
        public JsonResult ddlZParent(int ParentId)
        {
            var selectList = new SelectList(db.Categorys.Where(c => c.ParentId == ParentId).OrderByDescending(c => c.Sort).Select(c => new { c.Id, c.Name }), "Id", "Name");
            return this.Json(selectList, JsonRequestBehavior.AllowGet);
        }
        public JsonResult ddlChild(int ParentId)
        {
            var selectList = new SelectList(db.Categorys.Where(c => c.ParentId == ParentId).OrderByDescending(c => c.Sort).Select(c => new { c.Id, c.Name }), "Id", "Name");
            return this.Json(selectList, JsonRequestBehavior.AllowGet);
        }
        public JsonResult ddlBrand(int ParentId)
        {
            var brandList = db.Brands.OrderByDescending(b => b.Sort).Where(
                b => b.Category_Brands.Where(
                    cb => cb.CategoryId == ParentId).Select(cb => cb.BrandId).Contains(b.Id)
                );
            var itemBrandList = new SelectList(brandList, "Id", "Name");
            return this.Json(itemBrandList, JsonRequestBehavior.AllowGet);
        }
        #endregion
        /// <summary>
        /// 新建报价页分类下拉
        /// </summary>
        /// <param name="selected">选中项</param>
        private void ProductCreateDropDownList(object selected = null)
        {
            IList<Category> list = db.Categorys.OrderByDescending(p => p.Sort).Where(c => c.ParentId == null).ToList();
            //list.Insert(0, new Category() { Name = "添加为一级分类", Id = 0 });//添加默认第一列
            SelectList items = new SelectList(list, "Id", "Name", selected);

            ViewBag.Category = items;

            //子分类--------------------------------------------------------------------------------------------------------------
            int parentFirst = Convert.ToInt32(list.First().Id);

            var ChildList = db.Categorys.OrderByDescending(p => p.Sort).Where(c => c.ParentId == parentFirst).ToList();
            //list.Insert(0, new Category() { Name = "添加为一级分类", Id = 0 });//添加默认第一列
            SelectList itemChildList = new SelectList(ChildList, "Id", "Name");

            ViewBag.ChildList = itemChildList;
            //品牌----------------------------------------------------------------------------------------------------------------------
            SelectList itemBrandList;
            if (ChildList.Count > 0)
            {
                int childFirst = Convert.ToInt32(ChildList.First().Id);
                var brandList = db.Brands.OrderByDescending(b => b.Sort).Where(b => b.Category_Brands.Where(cb => cb.CategoryId == childFirst).Select(cb => cb.BrandId).Contains(b.Id));
                itemBrandList = new SelectList(brandList, "Id", "Name");
            }
            else
            {
                var brandList = db.Brands.OrderByDescending(b => b.Sort).Where(b => b.Category_Brands.Where(cb => cb.CategoryId == parentFirst).Select(cb => cb.BrandId).Contains(b.Id));
                itemBrandList = new SelectList(brandList, "Id", "Name");
            }
            // = new SelectList(brandList, "Id", "Name");
            ViewBag.BrandList = itemBrandList;
            //
        }
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }

    }
}
